package com.java.service.impl;

import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.java.entity.ExAdmin;
import com.java.mapper.ExAdminMapper;
import com.java.service.AdminService;
import com.java.util.MyCons;
import com.java.util.MyTools;
import com.java.util.resp.BaseRespone;
import com.java.util.servlet.ServletUtil;

@Service
public class AdminServiceImpl implements AdminService {
    private final Logger log = LoggerFactory.getLogger(getClass());

    @Autowired private ExAdminMapper adminMapper;

	@Override
	public BaseRespone login(String user, String password) {
		ExAdmin info = adminMapper.selectByInfo(new ExAdmin().setAdminUser(user));
		if(null == info) {
			return BaseRespone.error("管理员账号不存在");
		}
		if(!MyTools.getMD5(password).equals(info.getAdminPassword())) {
			return BaseRespone.error("账号密码错误");
		}
		ServletUtil.getSession().setAttribute(MyCons.ADMIN_ROLE, info);
		return BaseRespone.success("登陆成功");
	}

	@Override
	public ExAdmin getAdmin(String adminId) {
		return adminMapper.selectByKey(adminId);
	}

	@Override
	public BaseRespone update(ExAdmin admin) {
		ExAdmin info = adminMapper.selectByKey(admin.getAdminId());
		info.setAdminUser(admin.getAdminUser())
		.setAdminName(admin.getAdminName())
		.setAdminPassword(admin.getAdminPassword());
		int row = adminMapper.updateSelective(info);
		if(row == 0) {
			return BaseRespone.error("修改失败");
		}
		return BaseRespone.success("修改成功");
	}

	@Override
	public List<ExAdmin> getAdmins() {
		return adminMapper.selectAll(null, 0, 0);
	}

	@Override
	public BaseRespone save(ExAdmin admin) {
		int row = 0;
		ExAdmin adminInfo = adminMapper.selectByKey(admin.getAdminId());
		ExAdmin has = adminMapper.selectByInfo(new ExAdmin().setAdminUser(admin.getAdminUser()));
		if(null == adminInfo) {
			if(null != has) {
				return BaseRespone.error("该账号已存在");
			}
			adminInfo = new ExAdmin();
			adminInfo.setAdminId(MyTools.getUUID())
			.setAdminUser(admin.getAdminUser())
			.setAdminName(admin.getAdminName())
			.setAdminPassword(MyTools.getMD5(admin.getAdminPassword()))
			.setAdminTime(new Date());
			row = adminMapper.insertSelective(adminInfo);
		}else {
			if(null != has && !has.getAdminId().equals(admin.getAdminId())) {
				return BaseRespone.error("该账号已存在");
			}
			adminInfo.setAdminUser(admin.getAdminUser())
			.setAdminName(admin.getAdminName());
			if(!MyTools.isEmpty(admin.getAdminPassword())) {
				adminInfo.setAdminPassword(MyTools.getMD5(admin.getAdminPassword()));
			}
			row = adminMapper.updateSelective(adminInfo);
		}
		return BaseRespone.result(row, "保存成功", "保存失败");
	}

	@Override
	public BaseRespone delAdmin(String adminId) {
		int row = adminMapper.deleteByKey(adminId);
		return BaseRespone.result(row, "删除成功", "删除失败");
	}
    
    
}
